<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="addFn" :checked="isAll" @changeAll="changeAll"></TodoHeader>

    <TodoMain :list="showArr" 
    @change="changeFn" 
    @des="desFn"
    ></TodoMain>

    <TodoFooter :type="type" 
    :showArr="showArr"
    @changeType="changeTypeFn"
    @clearAll="clearAll"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  methods: {
    // 添加新的任务
    addFn(name) {
      this.list.push({
        id: this.list.length + 100,
        name: name,
        isDone: false,
      })
    },
    // 改变任务的状态
    changeFn(i){
      this.list[i].isDone=!this.list[i].isDone
    },
    // 删除任务
    desFn(i){
      this.list.splice(i,1)
    },
    // 切换不同状态的任务展示
    changeTypeFn(val){
      this.type=val
    },
    //接收TodoHeader传过来的全选框的值并改变list中每一项的isDone，使保持一致
    changeAll(val){
      this.list.forEach(i=>i.isDone=val)
    },
    //清楚全部已完成任务
    clearAll(){
      this.list=this.list.filter(i=>i.isDone===false)
      this.type='all'
    }
  },
  data() {
    return {
      //从本地获取存储的任务
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type:'all'
    }
  },
  watch: {
    //list发生变化就重新将list存储到本地
    list: {
      deep: true,
      immediate: true,
      handler(){
        localStorage.setItem('todoList',JSON.stringify(this.list))
      }
    },
  },
  computed:{
    //根据type值的不同筛选要展示的内容
    showArr(){
        switch(this.type){
          case 'yes':
            return this.list.filter(i=>i.isDone===true)
            case 'no':
              return this.list.filter(i=>i.isDone===false)
              default:
                return this.list
      }
    },
    //统计list中每一项isDone的值，如果全为true则返回true并传递给TodoHeader
    isAll(){
        return this.list.every(i=>i.isDone===true)
    }
  }
}
</script>
